
import { orderBuy, getOrderCoupon,orderPreview } from '../../api/store'
import { prepay, getMnpNotice } from '../../api/app'
import { Tips } from '../../utils/util'
import event from '../../utils/events'
import { payWay } from '../../utils/type'
import { wxpay } from '../../utils/wxutil'
import Toast from '../../components/weapp/toast/toast';
import Dialog from '../../components/weapp/dialog/dialog';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isFirstLoading: true,
        address: {},
        orderInfo: {},
        goodsLists: [],
        addressId: '',
        showCoupon: false,
        popActive: 0,
        couponCode:'',
        couponPrice:0,
        usableCoupon: [],
        unusableCoupon: [],
        userRemark: '',
        payWayArr: [
            {
                icon: '/images/icon_wechat.png',
                name: '微信支付',
                type: payWay.wechat,
                desc: '微信快捷支付'
            },
             /*{
                            icon: '/images/icon_wechat.png',
                            name: '余额支付',
                            type: payWay.blance,
                            desc: '微信快捷支付'
                        }*/
        ],
        payWay: payWay.wechat
    },

    radioChange(e) {
        this.setData({
            payWay: Number(e.detail.value)
        })
    },
    onSelectCoupon(e) {
console.log(e)
           this.couponPrice=e.detail.lastPrice;
           this.setData({ couponPrice: e.detail.lastPrice,couponCode: e.detail.code })

    },
    showCouponPop: function (e) {
        this.setData({ showCoupon: !this.data.showCoupon })
    },
    hideCouponPop: function (e) {
        this.setData({
            showCoupon: !this.data.showCoupon,
        })

    },
    onSelectAddress() {
        wx.navigateTo({
            url: `/pages/user_address/user_address?type=1`
        })
    },
    onRemarkChange(e) {
        let { detail } = e
        this.setData({
            userRemark: detail
        })
    },

    getAuthMsg() {
        return new Promise(resolve => {
            getMnpNotice({
                scene: 1
            }).then((res) => {
                if(res.code == 200) {
                    wx.requestSubscribeMessage({
                        tmplIds: res.data,
                        fail(res) {
                            console.log(res.errMsg)
                        },
                        complete() {
                            resolve()
                        }
                    })
                }
            })
        })
	},

    onSubmitOrder() {
        wx.showModal({
            title: '温馨提示',
            content: '是否确认下单',
            success: async (res) => {
                let { confirm } = res
                if (confirm) {
                   // await this.getAuthMsg()

                    this.toast = Toast.loading({
                        duration: 0, // 持续展示 toast
                        forbidClick: true,
                        message: '请稍等...',
                    });
                    this.$orderBuy('submit')
                }
            }
        })
    },
    $getOrderDetail(data) {
            orderPreview({skuInfo: data.skuInfo,
                          						isGroup: data.isGroup,
                          						groupId: data.groupId,
                          						ids: data.ids}).then(res => {
                if(res.code == 200) {
                    this.setData({
                                            settlement: res.data
                                        })
                                        wx.nextTick(() => {
                                                                this.setData({
                                                                    isFirstLoading: false
                                                                })
                                                            })
                }
            })
        },
    $getOrderCoupon() {
        return new Promise(resolve => {
            getOrderCoupon({
                goods: this.goods
            }).then(res => {
                if (res.code == 200) {
                    const { usable, unusable } = res.data
                    this.setData({
                        usableCoupon: usable,
                        unusableCoupon: unusable
                    })
                    resolve()
                }
            })
        })

    },

    $orderBuy(action = 'info') {
        let { address, userRemark, payWay, } = this.data
        let submitObj = {
            action,
            goods: this.goods,

        }

        if (action == 'info') {
            if (this.addressId) {
                submitObj.addressId = this.addressId
            }
        } else if (action == 'submit') {
        let storeinfos = [];
        let storeinfo = {};
    					storeinfo.storeId = 0;
    					storeinfo.payType = 0;
                        storeinfo.payStoreId= 0;
                        storeinfo.couponCode=this.data.couponCode
    					storeinfo.remark = userRemark || '';
    					storeinfos.push(storeinfo);

                        submitObj.ids = this.data.settlement.ids;
        				submitObj.skuInfo = this.data.settlement.skuInfo;
        				submitObj.redEnvelopeCode = this.data.settlement.redEnvelopeCode;
        				submitObj.isGroup = this.data.orderPreviewParam.isGroup;
        				submitObj.groupId = this.data.orderPreviewParam.groupId;
        				submitObj.source = 4;
        				submitObj.storeInfos = storeinfos;
            submitObj.remark = userRemark
            submitObj.addressId = address.id


        }
        orderBuy(submitObj).then(res => {
            if (res.code == 200) {
                if (action == 'info') {
                    let { address, goods_lists } = res.data
                    this.setData({
                        address,
                        goodsLists: goods_lists,
                        orderInfo: res.data,
                    })
                    wx.nextTick(() => {
                        this.setData({
                            isFirstLoading: false
                        })
                    })
                    return false
                } else if (action == 'submit') {
                    let { orderCode, orderMoney,needPay } = res.data
                    this.orderCode = orderCode
                    return prepay({
                        type: 1,
                        orderCode
                    })
                }
            } else {
                Toast.clear()
                Tips({ title: res.msg })
                return false
            }
        }).then(res => {
            Toast.clear()
            console.log(res)
            //      * @return 返回码和调起支付需要的参数 返回码说明  -1:用户不存在 -3:没有待支付的订单 -5:微信生成订单出错 -7 没有设置网站地址 -8 缺少配置  -10没有绑定微信 1 成功

            if (res.code == 200) {
            var r = res.data
            if(r.flag==-5){
            Tips({ title: '微信生成订单出错' })

            					return false;
            				}
            				if(r.flag==-3){
            				Tips({ title: '没有待支付订单' })
            					return false;
            				}
            				if(r.flag==-1){
                                        				Tips({ title: '用户不存在' })
                                        					return false;
                                        				}
            				if(r.flag==-7){
                                        				Tips({ title: '没有设置网站地址' })
                                        					return false;
                                        				}

            				if(r.flag==-8){
            				Tips({ title: '参数错误' })
            					return false;
            				}

                let args = res.data.data
                wxpay(args).then(()=> {
                    this.payStatus = true
					wx.redirectTo({
							url: `/pages/pay_result/pay_result?id=${this.orderCode}`
					})
                }).catch(() => {
                    
					this.payStatus = true
					wx.redirectTo({
							url: `/pages/user_order/user_order`
					})
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    console.log(options)
    if(!options){
             wx.switchTab({
                  	url: '/pages/index/index'
          	})
          	return;
    }
        let goods = JSON.parse(options.goods) || []
        console.log(goods)
        this.setData({
                                    orderPreviewParam: goods
                                })
        this.$getOrderDetail(goods);
        event.on('SELECT_ADDRESS', this.getAddress, this)
    },
    getAddress(e) {
        this.addressId = e.id
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: async function () {
       // await this.$getOrderCoupon()
        if (this.payStatus) return
       // this.$orderBuy()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        event.remove('SELECT_ADDRESS')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})